<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\library\Wechat;
use think\Cookie;

/**
 * 登录接口
 */
class Login extends Common
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->appsecret = '2f313021e6b047bd9df29022abec9c79';
        $this->appid = 'wxf08c56ad4c545275';
    }

    /**
     * 首页
     *
     */
    public function login()
    {
        $code=$this->request->request('code');
        $to =$this->getopenid($code);
        $access_token=$this->getAccessToken();
        $user = $this->getUserInfo($access_token,$to['openid']);

        $openid = $to['openid'];
        $user['openid'] = $openid;
        //判断当前用户是否存在
        $userInfo = $this->model
            ->where('openid', $openid)
            ->find();
        if (!$userInfo) {
            //新增用户
            $id = $this->model->insertGetId($user);
            if (!$id) {
                $this->outputError('登录失败');
            }
            $userDetail = $this->model
                ->where('id', $id)
                ->find();
        }else {
            $userDetail = $userInfo;
        }
        $smrz=Db('user_smrz')->where(['uid'=>$userDetail['id']])->find();
//        $data=['gllx'=>$smrz['gllx'],'dawe'=>$dawe,'bume'=>$bume,'zzfg'=>$zzfg,'image'=>$image];
        $userDetail['gllx']=$smrz['gllx'];
        $userDetail['dawe']=$smrz['dawe'];
        $userDetail['bume']=$smrz['bume'];
        $userDetail['status']=$smrz['status'];
        $userDetail['zzfg']=$smrz['zzfg'];
        $userDetail['image']=$smrz['image'];
        $this->outputData($userDetail);
    }

    /**
     * 用户状态
     */
	public function userdel()
    {
        $openid = $this->request->get('openid');
		if (!is_numeric($openid)) {
            $this->outputError('参数错误');
        }
		$userInfo = $this->model
			->alias('t')
            ->where('t.openid', $openid)
            ->find();
		$this->outputData($userInfo);
    }
    public function getCodeUrl(){
        $redirect_url = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=
        {$this->appid}&redirect_uri=".$redirect_url
            .'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        return $get_code_url;
    }

    /**
     * @param $code
     * @return bool|string
     * access_token 网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
    expires_in  access_token接口调用凭证超时时间，单位（秒）
    refresh_token   用户刷新access_token
    openid  用户唯一标识，请注意，在未关注公众号时，用户访问公众号的网页，也会产生一个用户和公众号唯一的OpenID
    scope   用户授权的作用域，使用逗号（,）分隔
     *
     * {"errcode":40029,"errmsg":"invalid code"}
     */
    public function getOpenId($code){
        $get_openid_url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appsecret}&js_code={$code}&grant_type=authorization_code";

        $rst = file_get_contents($get_openid_url);
        $rst = json_decode($rst, true);
        if(isset($rst['openid'])){
            return $rst;
        }else{
            return false;
        }
    }
    /**
     * @param $access_token
     * @param $open_id
     * @return bool|mixed
     * openid   用户的唯一标识
    nickname    用户昵称
    sex 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
    province    用户个人资料填写的省份
    city    普通用户个人资料填写的城市
    country 国家，如中国为CN
    headimgurl  用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空。若用户更换头像，原有头像URL将失效。
    privilege   用户特权信息，json 数组，如微信沃卡用户为（chinaunicom）
    unionid 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
     */
    public function getUserInfo($access_token, $open_id){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token
            .'&openid='.$open_id.'&lang=zh_CN';
        $rst = $this->https_request($url);
        $rst = json_decode($rst, true);
        if(isset($rst['errcode'])){
            return false;
        }else{
            return $rst;
        }
    }
    public function https_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public function getAccessToken(){
            $appId = $this->appid;
            $appSecret = $this->appsecret;//虚拟的，不要用
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
            $ch = curl_init();//初始化curl
            curl_setopt($ch, CURLOPT_URL, $url); //要访问的地址
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
            $data = json_decode(curl_exec($ch));
            if (curl_errno($ch)) {
                var_dump(curl_error($ch)); //若错误打印错误信息
            }
            $accessToken = $data->access_token;
        return $accessToken; //打印信息
        curl_close($ch);//关闭curl
    }

}
